package com.collectplus.express;

import android.app.Activity;
import android.content.Intent;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.collectplus.express.logic.AppCache;
import com.shouhuobao.bhi.login.LoginActivity;

import droid.frame.App;
import droid.frame.activity.title.TitleMgr;
import droid.frame.activity.title.TitleRes;
import droid.frame.fragment.FragmentMgr;
import droid.frame.fragment.FrameBaseFragment;
import droid.frame.ui.dialog.AppLoading;
import droid.frame.utils.android.SharedPref;

/**
 * 非public.用的时候直接拷贝到子项目中。用法同 {@link BaseActivity} 一样
 *
 * @author coffee<br>
 * 2014年9月19日下午3:42:50
 */
public abstract class BaseFragment extends FrameBaseFragment {

    protected final int CLOSE = 1000000;

    private TitleMgr titleMgr;

    private ProgressBar mProgressBar;
    private TextView mEmptyView;

    /**
     * 当前Fragment显示在前端
     */
    protected boolean isCurrentShow = true;

    protected SwipeRefreshLayout mSwipeLayout;

    public boolean isCurrentShow() {
        return isCurrentShow;
    }

    public void setCurrentShow(boolean isCurrentShow) {
        this.isCurrentShow = isCurrentShow;
    }

    @Override
    protected void findViewById() {
        super.findViewById();
        titleMgr = new TitleMgr(this);
        titleMgr.initTitle();
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
        //
        int loadingId = getResources().getIdentifier("loading_progressBar", "id", getActivityContext().getPackageName());
        if (loadingId != 0) {
            mProgressBar = (ProgressBar) findViewById(loadingId);
        }
        if (mProgressBar != null) {
            mProgressBar.setVisibility(View.GONE);
        }
        int emptyId = getResources().getIdentifier("empty_text", "id", getActivityContext().getPackageName());
        mEmptyView = (TextView) findViewById(emptyId);
        if (mEmptyView != null) {
            ((ViewGroup) mEmptyView.getParent()).setVisibility(View.GONE);
        }
    }

    protected void onRefreshComplete() {
        if (mSwipeLayout != null) {
            getActivityContext().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mSwipeLayout.setRefreshing(false);
                }
            });
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getActivityContext() != null && getActivityContext().getApplication() != null) {
            Thread.setDefaultUncaughtExceptionHandler(((ExpressApplication) getActivityContext().getApplication()).getUncaughtExceptionHandler());
        }
    }

    /**
     * 显示通用Title<br>
     * 调用该方法时需要确保子类成功调用了 {@link #findViewById()}
     */
    public void setCommonTitle(String titleText) {
        setTitle(new TitleRes[]{titleMgr.getBackTitle(), new TitleRes(0, titleText, null), null});
    }

    public void setTitleBackground(int backgroundRes) {
        View layout = findViewById(R.id.app_title_layout);
        layout.setBackgroundResource(backgroundRes);
    }

    public void setTitle(TitleRes... reses) {
        for (int i = 0; i < reses.length; i++) {
            TitleRes res = reses[i];
            if (i == 0) {
                titleMgr.handleTitle(titleMgr.getTitleLeft(), res, 0);
            } else if (i == 1) {
                titleMgr.handleTitle(titleMgr.getTitleMiddle(), res, 1);
            } else if (i == 2) {
                titleMgr.handleTitle(titleMgr.getTitleRight(), res, 2);
            }
        }
    }

    public boolean isEmpty(Object str) {
        if (str == null || str.toString().trim().length() == 0) {
            return true;
        } else {
            return false;
        }
    }

    public ExpressApplication getApp() {
        if (ExpressApplication.getContext() != null) {
            return (ExpressApplication) ExpressApplication.getContext();
        } else {
            return (ExpressApplication) getActivity().getApplication();
        }
    }

    public TitleMgr getTitleMgr() {
        return titleMgr;
    }

    public void showLoadingBar() {
        if (mProgressBar != null) {
            mProgressBar.setVisibility(View.VISIBLE);
        }
    }

    public void cancelLoadingBar() {
        getActivityContext().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mProgressBar != null) {
                    mProgressBar.setVisibility(View.GONE);
                }
            }
        });
    }

    /**
     * 该方法主要考虑到一个界面里多个EmptyView
     *
     * @param emptyText
     */
    protected void setEmptyTextView(TextView emptyText) {
        this.mEmptyView = emptyText;
    }

    public void setEmptyView(ViewGroup viewGroup, String emptyText) {
        if (mEmptyView == null) {
            return;
        }
        //
        if (viewGroup instanceof ListView || viewGroup instanceof GridView) {
            AbsListView mAbsListView = (AbsListView) viewGroup;
            if (mAbsListView == null || mAbsListView.getAdapter() == null || mAbsListView.getAdapter().getCount() == 0) {
                ((View) mEmptyView.getParent()).setVisibility(View.VISIBLE);
                if (isEmpty(emptyText) == false) {
                    mEmptyView.setText(emptyText);
                }
            } else {
                ((View) mEmptyView.getParent()).setVisibility(View.GONE);
            }
        }
        // else if (viewGroup instanceof XListView) {
        // XListView xListView = (XListView) viewGroup;
        // // XListView含有Footer
        // if (xListView == null || xListView.getListView().getAdapter() == null || xListView.getListView().getAdapter().getCount() <= 1) {
        // ((View) mEmptyView.getParent()).setVisibility(View.VISIBLE);
        // if (isEmpty(emptyText) == false) {
        // mEmptyView.setText(emptyText);
        // }
        // } else {
        // ((View) mEmptyView.getParent()).setVisibility(View.GONE);
        // }
        // }
    }

    public void showToast(final String content) {
        App.getHandler().post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getActivityContext(), content, Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void setSharedPref(String key, String value) {
        SharedPref.put(key, value);
    }

    protected String getSharedPref(String key) {
        return SharedPref.get(key);
    }

    public boolean handleMessage(final Message msg) {

        return false;
    }

    /**
     * ********* 加载框相关 **********
     */

    private AppLoading loading;

    public void showLoadingDialog(final String dialogMessage) {
        getActivityContext().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (loading != null && loading.isShowing()) {
                    loading.setMessage(dialogMessage);
                    return;
                } else {
                    loading = new AppLoading(getActivityContext());
                    loading.setMessage(dialogMessage);
                    loading.show();
                }
            }
        });
    }

    protected void cancelLoadingDialog() {
        getActivityContext().runOnUiThread(new Runnable() {
            public void run() {
                if (loading != null) {
                    loading.dismiss();
                }
            }
        });
    }

    public void setButtonEnableStyle(Button button, boolean enable) {
        int bottom = button.getPaddingBottom();
        int top = button.getPaddingTop();
        int right = button.getPaddingRight();
        int left = button.getPaddingLeft();
        if (enable) {
            button.setBackgroundResource(R.drawable.app_button_selector);
            button.setTextColor(getResources().getColorStateList(R.color.app_buttoncolor_selector));
        } else {
            button.setBackgroundResource(R.drawable.app_button_bg_disable);
            button.setTextColor(getResources().getColor(R.color.white));
        }
        button.setPadding(left, top, right, bottom);
    }

    private Class<?> nextActivity = null;
    private Intent oldIntent;

    public void startActivityWhenLogin(Class<?> activityClass, String... params) {
        nextActivity = activityClass;
        Intent intent = new Intent();
        if (isLogin() == false) {
            intent.setClass(getActivityContext(), LoginActivity.class);
        } else {
            intent.setClass(getActivityContext(), nextActivity);
        }
        for (int i = 0; i < params.length; i++) {
            if (i + 1 < params.length) {
                intent.putExtra(params[i].toString(), params[i + 1]);
            }
        }
        oldIntent = intent;
        startActivityForResult(intent, 9999);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 9999 && resultCode == Activity.RESULT_OK) {
            Intent intent = new Intent();
            intent.setClass(getActivityContext(), nextActivity);
            intent.putExtras(oldIntent);
            startActivity(intent);
        }
    }

    public void startActivity(Class<?> classActivity) {
        Intent intent = new Intent();
        intent.setClass(getActivityContext(), classActivity);
        startActivity(intent);
    }

    public void stopService(Class<?> service) {
        Intent intent = new Intent();
        intent.setClass(getActivityContext(), service);
        getActivityContext().stopService(intent);
    }

    /**
     * 判断用户是否登录
     *
     * @return
     */
    public boolean isLogin() {
        return AppCache.isLogin();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        FragmentMgr.getInstance((FragmentActivity) getActivityContext()).onDestroy((FragmentActivity) getActivityContext());
    }
}
